package com.sagereal.wtc.factorymode.Activity;

import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.sagereal.wtc.factorymode.R;

import java.io.IOException;

public class HeadsetActivity extends BaseActivity {
    private int mI = 0;
    private MediaRecorder mRecorder;
    private MediaPlayer mPlayer;
    private boolean mPermissionToRecordAccepted = false;
    private String[] mPermissions = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private Button mTestPass,mTestFail,mTestBtn;
    private TextView mTextView;
    private String mFileName;

    private BroadcastReceiver mHeadsetReceiver,mScreenReceiver;

    private Handler mHandler;
    private Runnable mStopRecordingRunnable;

    private boolean mIsRecording = false,mIsPlaying = false,mHasRecording = false;
    private long mRecordingStartTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_headset);
        setTitle(getString(R.string.title_headset_test));
        mFileName = getExternalFilesDir(null).getAbsolutePath() + "/recorded_audio.3gp";
        mTestPass = findViewById(R.id.test_pass);
        mTestFail = findViewById(R.id.test_fail);
        mTestBtn = findViewById(R.id.test_btn);
        mTextView = findViewById(R.id.notify_text);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED){
            showPermissionDialog();
        }

        mHandler = new Handler();
        mStopRecordingRunnable = this::stopRecording;

        initView();

        registerHeadsetReceiver();
        setupScreenReceiver();

    }
    /*提示权限需要申请*/
    private void showPermissionDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.permission_ask)
                .setMessage(R.string.permission_content)
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setPositiveButton(getString(R.string.go_set), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                })
                .setCancelable(false)
                .show();
    }

    private void registerHeadsetReceiver() {
        mHeadsetReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                    int state = intent.getIntExtra("state", -1);
                    switch (state) {
                        case 0:
                             /*耳机未插入*/
                            mTestBtn.setEnabled(false);
                            if (mRecorder != null) {
                                mHandler.removeCallbacks(mStopRecordingRunnable);
                                stopRecording();
                                stopPlaying();
                                mTextView.setText(R.string.retest);
                                mTestBtn.setText(R.string.retest);
                            }
                            Toast.makeText(context, R.string.headset_insert, Toast.LENGTH_SHORT).show();
                            break;
                        case 1:
                            /*耳机插入*/
                            Toast.makeText(context, R.string.headset_detected, Toast.LENGTH_SHORT).show();
                            if (ContextCompat.checkSelfPermission(HeadsetActivity.this, Manifest.permission.RECORD_AUDIO)
                                    != PackageManager.PERMISSION_GRANTED){
                                mTestBtn.setEnabled(false);
                                break;
                            }
                            mTestBtn.setEnabled(true);
                            break;
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(mHeadsetReceiver, filter);
    }

    private void setupScreenReceiver(){
        mScreenReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(Intent.ACTION_SCREEN_OFF.equals(action)){
                    mHandler.removeCallbacks(mStopRecordingRunnable);
                    stopRecording();
                    stopPlaying();
                    mTextView.setText(R.string.retest);
                    mTestBtn.setText(R.string.retest);
                    mTestPass.setEnabled(true);
                    mTestBtn.setEnabled(true);
                }
            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mScreenReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mHeadsetReceiver);
        unregisterReceiver(mScreenReceiver);
        stopRecording();
        stopPlaying();
    }

    private boolean isHeadsetPlugged() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            return audioManager.isWiredHeadsetOn() || audioManager.isBluetoothA2dpOn();
        }
        return false;
    }

    private void initView() {
        mTestBtn.setOnClickListener(v -> {
            if(isHeadsetPlugged()){
                mTestBtn.setEnabled(false);
                mTestPass.setEnabled(false);
                startRecording();
                // 停止录音并播放录音
                mHandler.postDelayed(mStopRecordingRunnable, 5000);
            }else{
                Toast.makeText(HeadsetActivity.this, R.string.headset_insert, Toast.LENGTH_SHORT).show();
                mTestPass.setEnabled(false);
                mTestBtn.setEnabled(false);
            }
        });
        // 测试通过
        mTestPass.setOnClickListener(v -> {
            if(mHasRecording){
                Intent intent = new Intent(HeadsetActivity.this, ItemTestActivity.class);
                intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1));
                intent.putExtra("status", "pass");
                intent.putExtra("check", getIntent().getStringExtra("check"));
                setResult(RESULT_OK , intent);
                finish();
            }else {
                mTestPass.setEnabled(false);
                Toast.makeText(this, R.string.mic_passbtn_notify, Toast.LENGTH_SHORT).show();
                new Thread(() -> {
                    try {
                        Thread.sleep(3000); // 等待Toast显示时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(() -> mTestPass.setEnabled(true));
                }).start();
            }
        });
        // 测试失败
        mTestFail.setOnClickListener(v -> {
            Intent intent = new Intent(HeadsetActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1));
            intent.putExtra("status", "fail");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
    }

    private void startRecording() {
        mTextView.setText(R.string.recording);
        mTestBtn.setText(R.string.recording);

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
            mRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mIsRecording = true;
        mRecordingStartTime = System.currentTimeMillis();
    }

    private void stopRecording() {
        mTextView.setText(R.string.recording_completion);
        mTestBtn.setText(R.string.testing);

        if (mRecorder != null){
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
        mIsRecording = false;
        playRecording();
    }

    private void playRecording() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
            mIsPlaying = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        mPlayer.setOnCompletionListener(mp -> {
            mTextView.setText(R.string.mic_testing_completion);
            mTestBtn.setText(R.string.retest);
            mTestBtn.setEnabled(true);
            mTestPass.setEnabled(true);
            mHasRecording = true;
            mIsPlaying = false;
        });
    }

    private void stopPlaying() {
        if (mPlayer != null && mIsPlaying) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
            mIsPlaying = false;
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!hasFocus) {
            onPause();
        }
    }

    protected void onPause(){
        super.onPause();
        // 停止录音
        if (mIsRecording) {
            mHandler.removeCallbacks(mStopRecordingRunnable);
            stopRecording();
        }

        // 停止播放
        if (mIsPlaying) {
            stopPlaying();
        }
        // 停止正在进行的录音和播放
        mTextView.setText(null);
        mTestBtn.setText(R.string.retest);
        mTestPass.setEnabled(true);
        mTestBtn.setEnabled(true);
    }

    protected void onResume(){
        super.onResume();
        mI++;
        if(mI > 1){
            Log.d("wentianci", "onResume: "+ mI);
            // 在 onResume 中再次检查相机权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                // 如果没有权限，则直接结束活动
                finish();
            }
        }
    }
}
